package com.bocloud.cmp.driver.convertor.os;

import java.util.List;

import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.Subnet;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.convertor.BeanConvert;
import com.bocloud.cmp.model.NetworkModel;
import com.bocloud.cmp.model.SubnetModel;
import com.google.common.collect.Lists;

public class ConvertNetworks implements BeanConvert<NetworkModel, Network> {

	@Override
	public List<NetworkModel> convertList(List<? extends Network> networks) {
		List<NetworkModel> models = Lists.newArrayList();
		for (Network network : networks) {
			models.add(convertModel(network));
		}
		return models;
	}

	@Override
	public NetworkModel convertModel(Network network) {
		if (null == network) {
			return null;
		}
		NetworkModel model = new NetworkModel();
		model.setAdminStateup(network.isAdminStateUp());
		model.setName(network.getName());
		model.setNetworkId(network.getId());
		model.setShared(network.isShared());
		model.setStatus(network.getStatus().name());
		model.setType(network.getNetworkType().name());
		model.setIsRouterExternal(network.isRouterExternal());
		model.setPhyNetwork(network.getProviderPhyNet());
		model.setSegmentationId(network.getProviderSegID());
		List<? extends Subnet> subnets = network.getNeutronSubnets();
		List<SubnetModel> subnetModels = Lists.newArrayList();

		if (null != subnets) {
			for (Subnet subnet : subnets) {
				subnetModels.add(convertSubnet(subnet));
			}
		}
		model.setSubnets(subnetModels);
		return model;
	}

	private SubnetModel convertSubnet(Subnet subnet) {
		SubnetModel model = new SubnetModel();
		model.setName(subnet.getName());
		model.setCidr(subnet.getCidr());
		model.setDhcpEnabled(subnet.isDHCPEnabled());
		model.setDnsNames(JSONObject.toJSONString(subnet.getDnsNames()));
		model.setSubnetId(subnet.getId());
		model.setIpVersion(subnet.getIpVersion().name());
		model.setNetworkId(subnet.getNetworkId());
		model.setGateway(subnet.getGateway());
		model.setHostRoutes(JSONObject.toJSONString(subnet.getHostRoutes().toString()));
		return model;
	}

}
